extends Node

# 卡牌管理器 - 负责卡牌数据加载、卡牌创建、卡组管理等功能

# 信号定义
signal deck_created(deck_name: String)

# 卡牌数据
var card_database: Dictionary = {}
var deck_database: Dictionary = {}

# 预制场景
var card_scene: PackedScene

func _ready():
	load_card_data()
	load_card_scene()

func load_card_data():
	"""加载卡牌数据"""
	var file_path = "res://data/cards.json"
	
	if FileAccess.file_exists(file_path):
		var file = FileAccess.open(file_path, FileAccess.READ)
		if file:
			var json_string = file.get_as_text()
			file.close()
			
			var json = JSON.new()
			var parse_result = json.parse(json_string)
			
			if parse_result == OK:
				var data = json.data
				
				# 加载卡牌数据
				if data.has("cards"):
					for card_data in data["cards"]:
						# 确保ID是整数类型
						var card_id = int(card_data["id"])
						card_database[card_id] = card_data
				
				# 加载卡组数据
				if data.has("decks"):
					deck_database = data["decks"]
				

			else:
				print("JSON解析失败: ", json.error_string)
		else:
			print("无法打开文件: ", file_path)
	else:
		print("文件不存在: ", file_path)

func load_card_scene():
	"""加载卡牌预制场景"""
	card_scene = preload("res://scenes/Card.tscn")
	if not card_scene:
		print("警告: 无法加载卡牌场景")

func create_card(card_id: int) -> Control:
	"""根据ID创建卡牌实例"""
	
	if not card_database.has(card_id):
		print("错误: 找不到ID为 ", card_id, " 的卡牌")
		return null
	
	if not card_scene:
		print("错误: 卡牌场景未加载")
		return null
	
	# 创建卡牌实例
	var card_instance = card_scene.instantiate() as Control
	if card_instance:
		# 设置卡牌数据
		var card_data = card_database[card_id]
		card_instance.set_card_data(card_data)
		
		# 设置节点名称为卡牌名称
		if card_data.has("name"):
			card_instance.name = card_data["name"]
		
		print("CardManager: 卡牌创建完成 - 名称: ", card_instance.name, " card_name: ", card_instance.card_name)
		return card_instance
	else:
		print("错误: 无法创建卡牌实例")
		return null

func create_deck(deck_name: String) -> Array[Control]:
	"""根据卡组名称创建卡组"""
	var deck: Array[Control] = []
	
	if not deck_database.has(deck_name):
		print("错误: 找不到名为 ", deck_name, " 的卡组")
		return deck
	
	var deck_data = deck_database[deck_name]
	if deck_data.has("cards"):
		for card_entry in deck_data["cards"]:
			var card_id = card_entry["id"]
			var count = card_entry["count"]
			
			# 根据数量创建卡牌
			for i in range(count):
				var card = create_card(card_id)
				if card:
					deck.append(card)
	

	
	# 发射卡组创建完成信号
	deck_created.emit(deck_name)
	
	return deck

func get_card_data(card_id: int) -> Dictionary:
	"""获取卡牌数据"""
	return card_database.get(card_id, {})

func get_all_cards() -> Dictionary:
	"""获取所有卡牌数据"""
	return card_database

func get_all_decks() -> Dictionary:
	"""获取所有卡组数据"""
	return deck_database

func shuffle_deck(deck: Array[Control]) -> Array[Control]:
	"""洗牌"""
	var shuffled_deck = deck.duplicate()
	shuffled_deck.shuffle()
	return shuffled_deck

func draw_cards(deck: Array[Control], count: int) -> Array[Control]:
	"""从卡组抽牌"""
	var drawn_cards: Array[Control] = []
	
	for i in range(min(count, deck.size())):
		if deck.size() > 0:
			drawn_cards.append(deck.pop_back())
	
	return drawn_cards

func get_card_by_effect(effect_type: String) -> Array[int]:
	"""根据效果类型获取卡牌ID列表"""
	var matching_cards: Array[int] = []
	
	for card_id in card_database.keys():
		var card_data = card_database[card_id]
		if card_data.get("effect", "") == effect_type:
			matching_cards.append(card_id)
	
	return matching_cards

func get_cards_by_type(card_type: String) -> Array[int]:
	"""根据卡牌类型获取卡牌ID列表"""
	var matching_cards: Array[int] = []
	
	for card_id in card_database.keys():
		var card_data = card_database[card_id]
		if card_data.get("type", "") == card_type:
			matching_cards.append(card_id)
	
	return matching_cards

func get_cards_by_cost(cost: int) -> Array[int]:
	"""根据费用获取卡牌ID列表"""
	var matching_cards: Array[int] = []
	
	for card_id in card_database.keys():
		var card_data = card_database[card_id]
		if card_data.get("cost", 0) == cost:
			matching_cards.append(card_id)
	
	return matching_cards

func get_cards_by_rarity(rarity: String) -> Array[int]:
	"""根据稀有度获取卡牌ID列表"""
	var matching_cards: Array[int] = []
	
	for card_id in card_database.keys():
		var card_data = card_database[card_id]
		if card_data.get("rarity", "") == rarity:
			matching_cards.append(card_id)
	
	return matching_cards
